package com.jiefutong.zyt.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiefutong.zyt.Constant;
import com.jiefutong.zyt.PermissionUtil;
import com.jiefutong.zyt.R;
import com.jiefutong.zyt.WebViewActivity;
import com.jiefutong.zyt.apiservice.ApiService;
import com.jiefutong.zyt.bean.MainVO;
import com.jiefutong.zyt.bean.MineVO;
import com.jiefutong.zyt.http.XCRRestProvider;
import com.jiefutong.zyt.utils.RoundTransform;
import com.jiefutong.zyt.view.MyDialog;
import com.jiefutong.zyt.zxing.app.CaptureActivity;
import com.sobot.chat.SobotApi;
import com.sobot.chat.SobotUIConfig;
import com.sobot.chat.api.model.Information;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by a2384760 on 2019/3/19.
 */

public class MainFragment  extends Fragment implements View.OnClickListener{
    View view;
    //搜索
    private LinearLayout searchLL;
    //消息
    private ImageView msgIV;
    //扫一扫
    private LinearLayout scanLL;
    //收支明细
    private LinearLayout budgetLL;
    //转账
    private LinearLayout transferLL;
    //账户总览
    private LinearLayout accountLL;
    //立即领取
    private RelativeLayout getRL;
    private ImageView getIV;
    //优惠券
    private ImageView couponIV;
    //分类gv
    private GridView titleGV;
    //内容gv
    private GridView contentGV;
    //附近商家
    private LinearLayout nearLL;
    private ListView nearLV;
    //猜你喜欢
    private GridView likeLV;


    private LinearLayout titleLL;
    private TextView searchTV;
    private ImageView searchIV;
    private ImageView guestIV;

    int mAlpha = 0;

    private ScrollView scrollView;
    ApiService apiService= XCRRestProvider.getInstance().create(ApiService.class);
    MainVO.DataBean dataBean;
    List< MainVO.DataBean.ToolsBean> dataList=new ArrayList<>();

    List< MainVO.DataBean.MerchsBean> shopList=new ArrayList<>();

    List< MainVO.DataBean.RecommendsBean> goodList=new ArrayList<>();

    private boolean isViewPrepared=false;//是否初始化完成
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_main,null);
        initView();
        if (!isViewPrepared&&getUserVisibleHint()) {//尚未初始化view,不能执行initData()方法[会报空指针]
            loadDatas();
        }
        isViewPrepared=true;//isViewPrepared判断和赋值位置不能变,考虑setUserVisibleHint更新数据
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        // 判断该Fragment时候已经正在前台显示，就可以知道什么时候去加载数据了

        if (isVisibleToUser && isViewPrepared) {
            loadDatas(); // 加载数据的方法
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    private void loadDatas() {
        showProgress(true);
   Call<MainVO> call=apiService.getMainInfo();
   call.enqueue(new Callback<MainVO>() {
       @Override
       public void onResponse(Call<MainVO> call, Response<MainVO> response) {
           if(response.isSuccessful()){
               MainVO mainVO=response.body();
               if(mainVO.getStatus().equals("success")){
                   dataBean=mainVO.getData();
                   dataList=mainVO.getData().getTools();
                   shopList=mainVO.getData().getMerchs();
                   goodList=mainVO.getData().getRecommends();
                   searchLL.setOnClickListener(MainFragment.this);
                   msgIV.setOnClickListener(MainFragment.this);
                   scanLL.setOnClickListener(MainFragment.this);
                   budgetLL.setOnClickListener(MainFragment.this);
                   transferLL.setOnClickListener(MainFragment.this);
                   accountLL.setOnClickListener(MainFragment.this);
                   if(dataBean.getIsreceive()==0){
                       getRL.setVisibility(View.VISIBLE);
                   }else{
                       getRL.setVisibility(View.GONE);
                   }
                   getIV.setOnClickListener(MainFragment.this);
                   ToolAdapter adapter=new ToolAdapter();
                   titleGV.setAdapter(adapter);
                   setListViewHeightBasedOnChildren(titleGV);
                   titleGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                       @Override
                       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                           MainVO.DataBean.ToolsBean goodsBean=dataList.get(position);
                           Intent intent=new Intent(getActivity(), WebViewActivity.class);
                           intent.putExtra("url",goodsBean.getUri());
                           intent.putExtra("title",goodsBean.getTitle());
                           startActivity(intent);
                       }
                   });

                   //附近的商家
                   ShopAdapter shopAdapter=new ShopAdapter();
                   nearLV.setAdapter(shopAdapter);
                   setViewHeightBasedOnChildren(nearLV);
                  //推荐商品
                   RecommedAdapter recommedAdapter=new RecommedAdapter();
                   likeLV.setAdapter(recommedAdapter);
                   setListViewHeightBasedOnChildren(likeLV);
                   likeLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                       @Override
                       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                           MainVO.DataBean.RecommendsBean recommendsBean=goodList.get(position);
                           Intent intent=new Intent(getActivity(), WebViewActivity.class);
                           intent.putExtra("url",recommendsBean.getUri());
                           intent.putExtra("title","商品详情");
                           startActivity(intent);
                       }
                   });


               }else{
                   Toast.makeText(getContext(),mainVO.getMessage(),Toast.LENGTH_SHORT).show();
               }
           }
           showProgress(false);
       }

       @Override
       public void onFailure(Call<MainVO> call, Throwable t) {
           showProgress(false);
           Toast.makeText(getContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
       }
   });
    }

    private void initView() {
        //搜索
        searchLL=view.findViewById(R.id.fragmentMain_searchLL);
        //消息
        msgIV=view.findViewById(R.id.fragmentMain_msgIV);
        //扫一扫
        scanLL=view.findViewById(R.id.fragmentMain_scanLL);
        //收支明细
         budgetLL=view.findViewById(R.id.fragmentMain_budgetLL);
        //转账
        transferLL=view.findViewById(R.id.fragmentMain_transferLL);
        //账户总览
        accountLL=view.findViewById(R.id.fragmentMain_accountLL);
        //立即领取
        getRL=view.findViewById(R.id.fragmentMain_getRL);
         getIV=view.findViewById(R.id.fragmentMain_getIV);
        //优惠券
         couponIV=view.findViewById(R.id.fragmentMain_couponIV);
        couponIV.setOnClickListener(this);
        //分类gv
        titleGV=view.findViewById(R.id.fragmentMain_titleGV);
        //内容gv
         contentGV=view.findViewById(R.id.fragmentMain_contentGV);
        //附近商家
        nearLL=view.findViewById(R.id.fragmentMain_nearLL);
        nearLL.setOnClickListener(this);
        nearLV=view.findViewById(R.id.fragmentMain_nearLV);
        //猜你喜欢
        likeLV=view.findViewById(R.id.fragmentMain_likeLV);

        scrollView=view.findViewById(R.id.fragmentMain_scrollView);

        titleLL=view.findViewById(R.id.fragmentMain_titleLL);
        searchTV=view.findViewById(R.id.fragmentMain_searchTV);
        searchIV=view.findViewById(R.id.fragmentMain_searchIV);
        guestIV=view.findViewById(R.id.fragmentMain_guestIV);
        guestIV.setOnClickListener(this);
        initNavigationBar();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    /**  ScrollView 滚动动态改变标题栏 */
                    // 滑动的最小距离（自行定义，you happy jiu ok）
                    int minHeight = 50;
                    // 滑动的最大距离（自行定义，you happy jiu ok）
                    int maxHeight = searchLL.getHeight() -minHeight;

                    // 滑动距离小于定义得最小距离
                    if (scrollView.getScrollY() <= minHeight) {
                        mAlpha = 0;
                    }
                    // 滑动距离大于定义得最大距离
                    else if (scrollView.getScrollY() > maxHeight) {
                        mAlpha = 255;
                    }
                    // 滑动距离处于最小和最大距离之间
                    else {
                        // （滑动距离 - 开始变化距离）：最大限制距离 = mAlpha ：255
                        mAlpha = (scrollView.getScrollY() - minHeight) * 255 / (maxHeight - minHeight);
                    }

                    // 初始状态 标题栏/导航栏透明等
                    if (mAlpha <= 0) {
                        setViewBackgroundAlpha(titleLL, 0);
                      //  titleLL.setBackgroundColor(Color.argb(255, 255, 255, 255));
                        searchLL.setBackgroundResource(R.drawable.corner_white);
                        searchIV.setImageResource(R.mipmap.jft_icon_search);
                        guestIV.setImageResource(R.mipmap.jft_but_customerservice);
                        msgIV.setImageResource(R.mipmap.jft_but_notice);
                        searchTV.setTextColor(Color.argb(255, 255, 255, 255));
                        //iconColorFilter(Color.parseColor("#ffffff"));

                    }
                    //  终止状态：标题栏/导航栏 不在进行变化
                    else if (mAlpha >= 255) {
                        setViewBackgroundAlpha(titleLL, 255);
                        searchLL.setBackgroundResource(R.drawable.corner_gray) ;
                        searchIV.setImageResource(R.mipmap.jft_icon_search1);
                        guestIV.setImageResource(R.mipmap.jft_but_customerservice1);
                        msgIV.setImageResource(R.mipmap.jft_but_notice1);
                        searchTV.setTextColor(Color.argb(255, 51, 51, 51));
                        //iconColorFilter(Color.parseColor("#000000"));

                    }
                    // 变化中状态：标题栏/导航栏随ScrollView 的滑动而产生相应变化
                    else {
                        setViewBackgroundAlpha(titleLL, mAlpha);
                        searchTV.setTextColor(Color.argb(255, 255 - mAlpha, 255 - mAlpha, 255 - mAlpha));
                        iconColorFilter(Color.argb(255, 255 - mAlpha, 255 - mAlpha, 255 - mAlpha));
                    }

                }
            });
        }


    }


    /**
     * 初始化导航栏
     * 包括：
     * 导航栏背景透明度，
     * 操作按钮颜色透明度，
     * 标题文字颜色等。
     */
    private void initNavigationBar() {
        setViewBackgroundAlpha(titleLL, 0);
        //iconColorFilter(Color.parseColor("#ffffff"));
    }

    /**
     * 标题栏/导航栏icon 颜色改变
     *
     * @param color
     */
    private void iconColorFilter(int color) {
        searchTV.setTextColor(0xffffffff);
      //  shareIcon.setColorFilter(colorFilter);
      //  searchIcon.setColorFilter(colorFilter);
       // backIcon.setColorFilter(colorFilter);
    }


    /**
     * 设置View的背景透明度
     *
     * @param view
     * @param alpha
     */
    public void setViewBackgroundAlpha(View view, int alpha) {
        if (view == null) return;

        Drawable drawable = view.getBackground();
        System.out.println("---------back:"+drawable.getAlpha());
        if (drawable != null) {
            drawable.setAlpha(alpha);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fragmentMain_searchLL:
                //搜索
                Intent intent=new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url",dataBean.getSearch().getUri());
                intent.putExtra("title","搜索");
                getActivity().startActivity(intent);
                break;
            case R.id.fragmentMain_msgIV:

                //消息
                Intent intent1=new Intent(getActivity(), WebViewActivity.class);
                intent1.putExtra("url",dataBean.getMessage().getUri());
                intent1.putExtra("title","消息");
                getActivity().startActivity(intent1);
                break;
            case R.id.fragmentMain_scanLL:
                //扫一扫
                new PermissionUtil(getActivity(), PermissionUtil.CAMERA) {
                    @Override
                    public void onsuccess() {
                        Intent intent2=new Intent(getActivity(), CaptureActivity.class);
                        //startActivityForResult(intent2, 100);
                        getActivity().startActivity(intent2);
                    }
                };

                break;
            case R.id.fragmentMain_budgetLL:
                //收支明细
                Intent intent3=new Intent(getActivity(), WebViewActivity.class);
                intent3.putExtra("url",dataBean.getFinance().getUri());
                intent3.putExtra("title",dataBean.getFinance().getTitle());
                getActivity().startActivity(intent3);
                break;
            case R.id.fragmentMain_transferLL:
                //转账
                Intent intent4=new Intent(getActivity(), WebViewActivity.class);
                intent4.putExtra("url",dataBean.getTransfer().getUri());
                intent4.putExtra("title",dataBean.getTransfer().getTitle());
                getActivity().startActivity(intent4);
                break;
            case R.id.fragmentMain_accountLL:
                //账户总览
                Intent intent5=new Intent(getActivity(), WebViewActivity.class);
                intent5.putExtra("url",dataBean.getAccounts().getUri());
                intent5.putExtra("title",dataBean.getAccounts().getTitle());
                getActivity().startActivity(intent5);
                break;
            case R.id.fragmentMain_getIV:
                //领取红包
                Intent intent6=new Intent(getActivity(), WebViewActivity.class);
                intent6.putExtra("url",dataBean.getRedpacket().getUri());
                intent6.putExtra("title",dataBean.getRedpacket().getTitle());
                getActivity().startActivity(intent6);
                break;
            case R.id.fragmentMain_couponIV:
                //债无忧
                input();
                break;
            case R.id.fragmentMain_guestIV:
                //客服
                Information info = new Information();
                info.setAppkey("82c234e35777444786715c6bad03ce41");
                info.setUname(dataBean.getUser_mobile());
                SobotUIConfig.sobot_titleBgColor = R.color.bg_screen;
                SobotUIConfig.sobot_titleTextColor= R.color.text_black_3;
                SobotUIConfig.sobot_chat_right_bgColor = R.color.text_black_3;
                SobotApi.startSobotChat(getActivity(), info);
                break;
            case R.id.fragmentMain_nearLL:
                Intent intent7=new Intent(getActivity(), WebViewActivity.class);
                intent7.putExtra("url",dataBean.getMoremerch());
                intent7.putExtra("title","商家列表");
                getActivity().startActivity(intent7);
                break;
        }
    }

    //债券
    MyDialog builder;
    public void input(){
        View view=View.inflate(getContext(),R.layout.dialog_bound,null);


        builder = new MyDialog(getContext(),0,0,view,R.style.dialog);
        builder.show();


    }

    public class ShopAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public class ViewHolder{
            private ImageView imgIV;
            private TextView titleTV;
            private TextView addressTV;
            private TextView telTV;
            private TextView directTV;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                convertView=View.inflate(getActivity(),R.layout.item_main_near,null);
                viewHolder=new ViewHolder();
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            final  MainVO.DataBean.MerchsBean data=shopList.get(position);
            viewHolder.imgIV=convertView.findViewById(R.id.itemMainNear_imgIV);
            viewHolder.titleTV=convertView.findViewById(R.id.itemMainNear_titleTV);
            viewHolder.addressTV=convertView.findViewById(R.id.itemMainNear_addressTV);
            viewHolder.telTV=convertView.findViewById(R.id.itemMainNear_telTV);
            viewHolder.directTV=convertView.findViewById(R.id.itemMainNear_directTV);

            if (!TextUtils.isEmpty(data.getPic())) {
                Picasso.with(getContext()).load(data.getPic()).transform(new RoundTransform(10)) .resize(200, 200).into(viewHolder.imgIV);
            }
            viewHolder.titleTV.setText(data.getTitle());
            viewHolder.addressTV.setText(data.getAddress());
            return convertView;
        }
    }

    public class ToolAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public class ViewHolder{
            private ImageView imgIV;
            private TextView titleTV;


        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           ViewHolder viewHolder=null;
            if(convertView==null){
                convertView=View.inflate(getActivity(),R.layout.item_gridview_title,null);
                viewHolder=new ViewHolder();
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            final  MainVO.DataBean.ToolsBean data=dataList.get(position);
            viewHolder.imgIV=convertView.findViewById(R.id.itemGridView_imgIV);
            viewHolder.titleTV=convertView.findViewById(R.id.itemGridView_textTV);

            if (!TextUtils.isEmpty(data.getIcon())) {
                Picasso.with(getContext()).load(data.getIcon()).resize(90, 90).into(viewHolder.imgIV);
            }
            viewHolder.titleTV.setText(data.getTitle());

            return convertView;
        }
    }


    public class RecommedAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return goodList.size();
        }

        @Override
        public Object getItem(int position) {
            return goodList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public class ViewHolder{
            private ImageView imgIV;
            private TextView titleTV;
            private TextView priceTV;
            private TextView buyTV;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           ViewHolder viewHolder=null;
            if(convertView==null){
                convertView=View.inflate(getActivity(),R.layout.item_mine_recommend,null);
                viewHolder=new ViewHolder();
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            final MainVO.DataBean.RecommendsBean data=goodList.get(position);
            viewHolder.imgIV=convertView.findViewById(R.id.itemRecommend_imgIV);
            viewHolder.titleTV=convertView.findViewById(R.id.itemRecommend_titleTV);
            viewHolder.priceTV=convertView.findViewById(R.id.itemRecommend_priceTV);
            viewHolder.buyTV=convertView.findViewById(R.id.itemRecommend_buyTV);
            if (!TextUtils.isEmpty(data.getPic())) {
                Picasso.with(getContext()).load(data.getPic()).transform(new RoundTransform(10)).into(viewHolder.imgIV);
            }
            viewHolder.titleTV.setText(data.getTitle());
            viewHolder.priceTV.setText("￥"+data.getMinprice());

            return convertView;
        }
    }


    /**
     * 动态设置ListView的高度
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 5;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
      /*  // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);*/
        // 设置参数
        listView.setLayoutParams(params);
    }



    /**
     * 动态设置ListView的高度
     * @param listView
     */
    public static void setViewHeightBasedOnChildren(ListView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 5;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i ++) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
      /*  // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);*/
        // 设置参数
        listView.setLayoutParams(params);
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    private ProgressDialog progress;
    public void showProgress(final boolean show) {
        if (progress == null) {
            progress = new ProgressDialog(
                    getActivity());
            progress.setMessage("正在加载...");
            progress.setCanceledOnTouchOutside(false);
        }

        if (show) {
            progress.show();
        } else {
            progress.dismiss();
        }
    }
}
